package com.luojiaoj

import com.luojiaoj.location.Province
import com.luojiaoj.location.City
import com.luojiaoj.location.School
import com.luojiaoj.type.LanguageType
import com.luojiaoj.update.Photo

class User {

	transient springSecurityService

	String username
	String password
    String email
	boolean enabled
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired

    Province province
    City city
    School school

    String nickname
    String motto
    Date birthday
    LanguageType languageType
    Photo avatar

	static constraints = {
		username blank: false, unique: true, minSize: 5
		password blank: false, minSize: 5
        email blank: false, email: true
        province nullable: true
        city nullable: true
        school nullable: true
        nickname nullable: true, size: 0..16
        motto nullable: true, size: 0..255
        birthday nullable: true
        languageType nullable: true
        avatar nullable: true
	}

	static mapping = {
		password column: '`password`'
	}

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this).collect { it.role } as Set
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = springSecurityService.encodePassword(password)
	}
}
